const path = require('path');
const merge = require('webpack-merge');
const TerserPlugin = require('terser-webpack-plugin');
const commonConfig = require('./webpack.base.config.js');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');

const CSS_MODULE_LOADER = {
  loader: 'css-loader',
  options: {
    modules: true,
  },
};
const POST_CSS_LOADER = {
  loader: 'postcss-loader',
  options: {
    plugins: () => [require('autoprefixer')],
  },
};
module.exports = merge(commonConfig, {
  mode: 'production',
  output: {
    path: path.resolve(__dirname, '../build'),
    filename: '[name].[contenthash:5].js',
    chunkFilename: '[name].[contenthash:5].chunk.js',
  },
  devtool: 'cheap-module-source-map',
  module: {
    rules: [
      {
        test: /\.(sc|sa|c)ss$/,
        exclude: /\.module\.(sc|sa|c)ss$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', POST_CSS_LOADER, 'sass-loader'],
      },
      {
        test: /\.module\.(sc|sa|c)ss$/,
        use: [MiniCssExtractPlugin.loader, CSS_MODULE_LOADER, POST_CSS_LOADER, 'sass-loader'],
      },
      {
        test: /\.less$/,
        use: [MiniCssExtractPlugin.loader, CSS_MODULE_LOADER, POST_CSS_LOADER, 'less-loader'],
      },
    ],
  },
  optimization: {
    // js Tree Shaking 清除到代码中无用的js代码，只支持import方式引入，不支持commonjs的方式引入
    usedExports: true,
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          parse: {
            ecma: 8,
          },
          compress: {
            ecma: 5,
            inline: 2,
            warnings: false,
            comparisons: false,
          },
          mangle: {
            safari10: true,
          },
          output: {
            ecma: 5,
            comments: false,
            ascii_only: true,
          },
        },
        parallel: true,
        cache: true,
        sourceMap: true,
      }),
      new OptimizeCssAssetsPlugin({
        cssProcessorOptions: {
          map: {
            safe: true,
            inline: false,
            annotation: true,
            mergeLonghand: false,
            autoprefixer: {disable: true},
            discardComments: {
              removeAll: true,
            },
          },
        },
        canPrint: true,
      }),
    ],
  },
  plugins: [
    new CompressionPlugin({
      minRatio: 0.8,
      threshold: 10240,
      algorithm: 'gzip',
      filename: '[path].gz[query]',
      test: new RegExp('\\.(js|scss|less|sass|css)$'),
    }),
  ],
});
